import {Component, EventEmitter, Input, OnInit, Output} from '@angular/core';
import {FormBuilder, FormControl, FormGroup, ValidationErrors, Validators} from '@angular/forms';
import {BaseService} from '../../../shared/service/base.service';
import {Observable, Observer} from "rxjs";
import {ApiUrl} from "../../../config/api-url";

@Component({
  selector: 'app-merchant-edit',
  templateUrl: './merchant-edit.component.html',
  styleUrls: ['./merchant-edit.component.less']
})
export class MerchantEditComponent implements OnInit {

  // 模态框显隐
  @Input()
  isVisible = false;
  // 父子互传值
  @Output()
  emit: EventEmitter<any> = new EventEmitter();
  // 提交时提交按钮是否加载中
  isOkLoading: any;
  // 模态框表单
  formModel: FormGroup;
  // 获取短信定时
  smsCodeText = '发送验证码';
  timer: any;
  time: number;
  smsCodeStatus = false;
  isLoadingOne: boolean;

  constructor(private fb: FormBuilder, private baseService: BaseService) {
  }

  ngOnInit(): void {
    this.buildForm();
  }


  buildForm() {
    this.formModel = this.fb.group({
      mobile: [null, [Validators.required], [this.mobileValidator]],
      password: [null, [Validators.required], [this.passwordValidator]],
      name: [null, [Validators.required]],
      smsCode: [null, [Validators.required]]
    });
  }


  /**
   * 手机号验证
   * @param control
   */
  mobileValidator = (control: FormControl) =>
    new Observable((observer: Observer<ValidationErrors | null>) => {
      let reg = /^0?(13|14|15|17|18)[0-9]{9}$/;
      let valid = reg.test(control.value);
      if (!valid) {
        observer.next({error: true, mobile1: true});
        observer.complete();
      } else {
        this.baseService.promise((resolve) => {
          this.baseService.get(ApiUrl.UserUrl + '/checkMobileAndUsername?mobile=' + control.value).subscribe(
            data => {
              resolve(data);
            });
        }).then((data: any) => {
          if (data.status == 1) {
            observer.next({error: true, duplicated: true});
          } else {
            observer.next(null);
          }
          observer.complete();
        });
      }
    });


  /**
   * 密码验证
   * @param control
   */
  passwordValidator = (control: FormControl) =>
    new Observable((observer: Observer<ValidationErrors | null>) => {
      if (control.value.length < 6) {
        observer.next({duplicated: true, error: true});
        observer.complete();
      } else {
        observer.next(null);
        observer.complete();
      }
    });

  // 取消
  handleCancel() {
    this.isVisible = false;
    this.formModel?.reset({});
    this.emit.emit(this.isVisible);
  }

  // 确认
  handleOk() {
    this.isOkLoading = true;
    if (!this.baseService.zorro.validateFormValidate(this.formModel)) {
      this.isOkLoading = false;
      return;
    }

    if (!this.isOkLoading) {
      return;
    }
    this.baseService.post(ApiUrl.UserUrl + '/register', this.formModel.value).subscribe(res => {
      if (res.status == 0) {
        this.baseService.layer.messageSuccess("注册成功");
        this.handleCancel();
        this.isOkLoading = false;
      } else {
        this.baseService.layer.messageError(res.msg);
        this.isOkLoading = false;
      }
    });
  }


  sendCode() {
    let reg = /^0?(13|14|15|17|18)[0-9]{9}$/;
    if (!reg.test(this.formModel.get("mobile").value)) {
      this.baseService.layer.messageError("请填写正确的手机号码!")
      return;
    }
    this.isLoadingOne = true;
    this.baseService.get(ApiUrl.UserUrl + '/registerSmsCode', this.formModel.get("mobile").value).subscribe(res => {
      if (res.status == 0) {
        clearInterval(this.timer);
        this.time = 59;
        this.smsCodeStatus = true;
        this.timer = setInterval(() => {
          if (this.time > 0) {
            this.time--;
            this.smsCodeText = this.time + '秒 重新发送';
          } else {
            this.smsCodeText = '重新发送';
            this.smsCodeStatus = false;
            clearInterval(this.timer); //清除计时器
          }
          this.isLoadingOne = false;
        }, 1000);
        this.baseService.layer.messageSuccess(res.data);
      } else {
        this.isLoadingOne = false;
        this.baseService.layer.messageError(res.msg);
      }
    });
  }
}
